<template>
  <div class="flex ml-20px">
    <div class="tableManage w-100%">
      <ContentWrap>
        <!-- 搜索区域 -->
        <div class="search-form">
          <Search
            :schema="allSchemas.searchSchema"
            @reset="handleSearchReset"
            @search="handleSearch"
          />
        </div>

        <ElDivider />

        <!-- 操作按钮区域 -->
        <div class="mb-10px">
          <BaseButton class="opBtn" type="primary" @click="handleAdd">
            新增
          </BaseButton>
          <el-upload
            ref="uploadRef"
            class="opBtn-upload"
            :auto-upload="false"
            :show-file-list="false"
            :accept="'.xlsx,.xls'"
            :on-change="handleFileSelect"
          >
            <BaseButton class="opBtn" size="" type="primary"
              >导入数据</BaseButton
            >
          </el-upload>
          <BaseButton type="primary" @click="exportActionExcel">
            下载模板
          </BaseButton>
        </div>

        <!-- 表格区域 -->
        <Table
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :columns="allSchemas.tableColumns"
          :data="dataList"
          :loading="loading"
          :pagination="{ total }"
          @register="tableRegister"
        />
      </ContentWrap>
    </div>

    <!-- 弹窗对话框 -->
    <Dialog width="65%" v-model="dialogVisible" :title="dialogTitle">
      <!-- 表单组件 -->
      <Write
        v-if="actionType !== 'detail'"
        ref="writeRef"
        class="opWrite"
        :form-schema="filteredFormSchema"
        :current-row="currentRow as any"
      />

      <!-- 详情组件 -->
      <Detail
        v-if="actionType === 'detail'"
        :detail-schema="allSchemas.detailSchema"
        :current-row="currentRow as any"
      />

      <!-- 弹窗底部 -->
      <template #footer>
        <BaseButton
          v-if="actionType !== 'detail'"
          type="primary"
          :loading="saveLoading"
          @click="handleSave"
        >
          保存
        </BaseButton>
        <BaseButton @click="dialogVisible = false"> 关闭 </BaseButton>
      </template>
    </Dialog>

        <Dialog v-model="resultDialogVisible" :title="importTitle" width="50%">




        <div class="import-result" >
          <div
            class="import-result-container"
            :style="{ height: resultContainerHeight }"
          >

            <div
             v-for="(error, index) in tabs1"
                :key="index"
              class="demo-tabs full-height-tabs"
            >

                <!-- 移除外层的 flex 布局，使用简单的固定高度 -->
                <div class="error-content-wrapper">

                    <div
                      class="error-item"

                    >
                      <h4 class="mb-10px">{{ error.dataRow }}:</h4>
                      <p
                        class="mb-5px"
                        v-for="(item, i) in error.errors"
                        :key="i"
                      >
                        {{ item }}
                      </p>
                    </div>


                </div>

            </div>
          </div>
        </div>


      <template #footer>
        <BaseButton type="primary" @click="resultDialogVisible = false">
          确定
        </BaseButton>
      </template>
    </Dialog>
  </div>
</template>

<script setup lang="tsx">
import { directAxios } from "@/axios/index";

import { ref, unref, reactive, watch, computed, nextTick, onMounted, onUnmounted } from "vue";
import { ElDivider, ElSwitch, ElMessageBox, ElMessage ,ElUpload,
  UploadFile,
  UploadInstance,} from "element-plus";
import { Edit, View, Delete } from "@element-plus/icons-vue";
import axios from "axios";


// 组件导入
import { ContentWrap } from "@/components/ContentWrap";
import { Table } from "@/components/Table";
import { Search } from "@/components/Search";
import { Dialog } from "@/components/Dialog";
import { BaseButton } from "@/components/Button";
import Write from "./components/CompanyManagementWrite.vue";
import Detail from "./components/CompanyManagementDetail.vue";

// Hooks 导入
import { useValidator } from "@/hooks/web/useValidator";
import { useTable } from "@/hooks/web/useTable";
import { CrudSchema, useCrudSchemas } from "@/hooks/web/useCrudSchemas";
import { useDepartmentStore } from "@/store/modules/departmentStore";

// 类型定义
interface FormData {
  loginCodeEffectiveDate?: string;
  loginCodeExpiryDate?: string;
  [key: string]: any;
}

interface TableRow {
  id?: string;
  enabled?: string;
  [key: string]: any;
}

// 常量定义

const ENABLED_STATUS = {
  ENABLED: "启用",
  DISABLED: "禁用",
};


// 添加响应式高度控制
const resultContainerHeight = ref("400px"); // 默认高度
const errorContentHeight = ref("300px"); // 错误内容区域高度

const calculateHeights = () => {
  const windowHeight = window.innerHeight;
  const dialogHeight = windowHeight * 0.7;
  resultContainerHeight.value = `${dialogHeight - 120}px`;
  errorContentHeight.value = `${dialogHeight - 250}px`; // 调整这个值，为 tabs 头部留出空间
};
// Store 和 Hooks 初始化
const { required } = useValidator();
const departmentStore = useDepartmentStore();

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState;
    const res = await "/api/deviceManufacturer/search".get({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams),
    });

    return {
      list: res.data.records || [],
      total: res.data.total || 0,
    };
  },
});

// 响应式数据
const { total, loading, dataList, pageSize, currentPage } = tableState;
const { getList } = tableMethods;

const searchParams = ref({});
const dialogVisible = ref(false);
const dialogTitle = ref("");
const currentRow = ref<TableRow>();
const actionType = ref("");
const writeRef = ref();
const saveLoading = ref(false);
const currentNodeKey = ref(departmentStore.currentNodeKey);

// 监听器
watch(
  () => departmentStore.currentNodeKey,
  (newKey) => {
    console.log("store中的currentNodeKey变化", newKey);
    if (newKey && newKey !== currentNodeKey.value) {
      currentNodeKey.value = newKey;
    }
  }
);


const validateExpiryDate = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error("请选择登录码失效时间"));
    return;
  }

  // 获取表单数据
  const write = unref(writeRef);
  const formData = write?.getFormData?.();

  if (formData && formData.loginCodeEffectiveDate) {
    const effectiveDate = new Date(formData.loginCodeEffectiveDate);
    const expiryDate = new Date(value);

    if (expiryDate <= effectiveDate) {
      callback(new Error("登录码失效时间必须晚于生效时间"));
      return;
    }
  }

  callback();
};

const validateFormData = (formData: FormData): string | null => {
  const { loginCodeEffectiveDate, loginCodeExpiryDate } = formData;

  if (!loginCodeEffectiveDate || !loginCodeExpiryDate) {
    return null; // 必填验证已经在表单规则中处理
  }

  const effectiveDate = new Date(loginCodeEffectiveDate);
  const expiryDate = new Date(loginCodeExpiryDate);
  console.log("生效时间:", effectiveDate);
  console.log("失效时间:", expiryDate);
  // 移除了与当前时间的比较，只比较生效时间和失效时间
  if (expiryDate < effectiveDate) {
    return "登录码失效时间必须晚于生效时间";
  }

  return null;
};

// CRUD Schemas 配置
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: "selection",
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true },
    table: { type: "selection", hidden: true },
  },
  {
    field: "index",
    label: "序号",
    form: { hidden: true },
    search: { hidden: true },
    detail: { hidden: true },
    table: { type: "index" },
  },
  {
    field: "name",
    label: "单位名称",
    from: {
      component: "Input",

      formItemProps: {
        rules: [
          { required: true, message: "请输入单位名称" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入单位名称" },
        ],
      },

      componentProps: {
        placeholder: "请输入单位名称",
      },
    },

    search: {
      component: "Input",
      label: "",
      hidden: false,
      componentProps: {
        placeholder: "单位名称",
      },
    },
  },
  {
    field: "loginCode",
    label: "登录码",
    width: 150,
    search: {
      component: "Input",
      label: "",
      hidden: true,
      componentProps: {
        placeholder: "登录码",
      },
    },
    form: {
      hidden: false,
      component: "Input",
      componentProps: {
        placeholder: "请输入登录码",
        disabled: true,
      },
    },
    detail: { hidden: false },
  },
  {
    field: "loginCodeEffectiveDate",
    label: "登录码生效时间",
    width: 150,
    search: {
      component: "DatePicker",
      label: "",
      hidden: true,
      componentProps: {
        type: "date",
        valueFormat: "YYYY-MM-DD",
        placeholder: "登录码生效时间",
      },
    },
    form: {
      hidden: false,
      component: "DatePicker",
      formItemProps: {
        rules: [
          {
            required: true,
            message: "请选择登录码生效时间",
          },
        ],
      },
      componentProps: {
        type: "date",
        valueFormat: "YYYY-MM-DD",
        placeholder: "请选择登录码生效时间",
      },
    },
    detail: { hidden: false },
  },
  {
    field: "loginCodeExpiryDate",
    label: "登录码失效时间",
    width: 150,
    search: {
      component: "DatePicker",
      label: "",
      hidden: true,
      componentProps: {
        type: "date",
        valueFormat: "YYYY-MM-DD",
        placeholder: "登录码失效时间",
      },
    },
    form: {
      hidden: false,
      component: "DatePicker",
      formItemProps: {
        rules: [
          required(),
          { validator: validateExpiryDate, trigger: "change" },
        ],
      },
      componentProps: {
        type: "date",
        valueFormat: "YYYY-MM-DD",
        placeholder: "请选择登录码失效时间",
      },
    },
    detail: { hidden: false },
  },

  {
    field: "enabled",
    label: "是否启用",
    search: {
      component: "Select",
      hidden: true,
      componentProps: {
        placeholder: "启用状态",
        options: [
          { label: ENABLED_STATUS.ENABLED, value: ENABLED_STATUS.ENABLED },
          { label: ENABLED_STATUS.DISABLED, value: ENABLED_STATUS.DISABLED },
        ],
      },
    },
    detail: {
       hidden: true,
    },
    form: {
       hidden: true,
      component: "RadioGroup",
      value: ENABLED_STATUS.ENABLED,
      formItemProps: {
        rules: [{ required: true, message: "请选择是否启用" }],
      },
      componentProps: {
        options: [
          { label: ENABLED_STATUS.ENABLED, value: ENABLED_STATUS.ENABLED },
          { label: ENABLED_STATUS.DISABLED, value: ENABLED_STATUS.DISABLED },
        ],
      },
      colProps: { span: 12 },
    },
    table: {
       hidden: true,
      slots: {
        default: ({ row }) => {
          return (
            <ElSwitch
              inline-prompt
              active-text="启用"
              inactive-text="禁用"
              modelValue={row.enabled === ENABLED_STATUS.ENABLED}
              onChange={() => handleStatusUpdate(row)}
            />
          );
        },
      },
    },
  },
  {
    field: "shortName",
    label: "简称",
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入简称" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入简称" },
        ],
      },
      componentProps: {
        placeholder: "请输入简称",
      },
    },
    search: {
      component: "Input",
      label: "",
      hidden: false,
      componentProps: {
        placeholder: "简称",
      },
    },
  },
  {
    field: "type",
    label: "类别",
    form: {
      component: "Input",

      componentProps: {
        placeholder: "请输入类别",
      },
    },
    search: {
      component: "Input",
      label: "",
      hidden: true,
      componentProps: {
        placeholder: "类别",
      },
    },
  },
  {
    field: "contact",
    label: "联系方式",
    search: { hidden: true },
    form: {
      component: "Input",
      componentProps: {
        placeholder: "请输入联系方式",
      },
      formItemProps: {
        rules: [
          { required: true, message: "请输入联系方式" },
          { pattern: /^[0-9]{11}$/, message: "请输入正确的联系方式" },
        ],
      },
      colProps: { span: 12 },
    },
  },
  {
    field: "action",
    label: "操作",
    fixed: "right",
    form: { hidden: true },
    detail: { hidden: true },
    search: { hidden: true },
    table: {
      width: 170,
      fixed: "right",
      slots: {
        default: (data: any) => {
          const row = data.row;
          return (
            <>
              <div style="display:flex;color: var(--el-color-primary)">
                  <div
                  class="flex-1 cursor-pointer"
                  onClick={() => action(row, "edit")}
                >
                  <el-icon>
                    <Edit />
                  </el-icon>
                  编辑
                </div>
                <div
                  class="flex-1 action-btn cursor-pointer"
                  onClick={() => handleAction(row, "detail")}
                >
                  <el-icon>
                    <View />
                  </el-icon>
                  查看
                </div>

                <div class="action-btn cursor-pointer" onClick={() => handleDelete(row)}>
                  <el-icon>
                    <Delete />
                  </el-icon>
                  删除
                </div>
              </div>
            </>
          );
        },
      },
    },
  },
]);

const { allSchemas } = useCrudSchemas(crudSchemas);

// 计算属性
const filteredFormSchema = computed(() => {
  return allSchemas.formSchema.filter((item) => !item.hidden);
});

// 事件处理函数
const handleSearchReset = (params: any) => {
  setSearchParams(params);
};

const handleSearch = (params: any) => {
  setSearchParams(params);
};

const setSearchParams = (params: any) => {
  currentPage.value = 1;
  searchParams.value = params;
  getList();
};

const handleAdd = () => {
  dialogTitle.value = "新增";
  currentRow.value = undefined;
  dialogVisible.value = true;
  actionType.value = "";
};

const handleAction = (row: TableRow, type: string) => {
  dialogTitle.value = "查看";
  actionType.value = type;
  currentRow.value = row;
  dialogVisible.value = true;
};
const action = (row: TableRow, type: string) => {
  dialogTitle.value ="编辑" ;
  actionType.value = type;
  currentRow.value = row;
  dialogVisible.value = true;
};
const handleDelete = async (row: TableRow) => {
  try {
    await ElMessageBox.confirm("是否确认删除?", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    });

    const res = await directAxios.get(
      `/api/deviceManufacturer/delete/${row?.id}`
    );
    if (res.code === 200) {
      ElMessage.success("删除成功");
      getList();
    }
  } catch (error) {
    // 用户取消删除，不做任何操作
  }
};

const handleSave = async () => {
  const write = unref(writeRef);
  if (!write) return;

  // 表单基础验证
  const formData = await write.submit?.();
  if (!formData) return;

  // 自定义验证
  const validationError = validateFormData(formData);
  if (validationError) {
    ElMessage.error(validationError);
    return;
  }

  saveLoading.value = true;
  try {
    const res = await "/api/deviceManufacturer/save".post(formData);
    if (res) {
      currentPage.value = 1;
      getList();
      dialogVisible.value = false;
      ElMessage.success("保存成功");
    }
  } catch (error) {
    console.error("保存失败:", error);
    ElMessage.error("保存失败");
  } finally {
    saveLoading.value = false;
  }
};

const handleStatusUpdate = (row: TableRow) => {
  const { enabled } = row;
  const text =
    enabled === ENABLED_STATUS.ENABLED ? "确定要禁用吗？" : "确定要启用吗？";

  ElMessageBox.confirm(text, {
    title: "提示",
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      console.log(row, "更新状态");
      // 这里添加实际的状态更新逻辑
    })
    .catch(() => {
      console.log(row, "取消");
    });
};

// ============ 导入导出功能 ============
const uploadRef = ref<UploadInstance>();
const resultDialogVisible = ref(false);
const selectedFile = ref<File | null>(null);
const importTitle = ref("");
const tabs1 = ref();
const importLoading = ref(false);
/**
 * 验证文件类型
 */
const validateFileType = (file: UploadFile) => {
  if (!file.raw) {
    ElMessage.error("文件不存在");
    return false;
  }

  // 检查文件扩展名
  const fileExtension = file.name.split(".").pop()?.toLowerCase();
  const allowedExtensions = ["xls", "xlsx"];

  if (!fileExtension || !allowedExtensions.includes(fileExtension)) {
    ElMessage.error("文件格式错误！只能上传 .xlsx 或 .xls 格式的Excel文件");
    return false;
  }

  // 检查MIME类型（可选，因为不同浏览器可能识别不同）
  const allowedMimeTypes = [
    "application/vnd.ms-excel",
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    "application/vnd.ms-excel.sheet.macroEnabled.12",
    "application/octet-stream", // 某些情况下可能是这个类型
  ];

  // 如果MIME类型不为空且不在允许列表中，给出警告但继续（因为扩展名正确）
  if (file.raw.type && !allowedMimeTypes.includes(file.raw.type)) {
    console.warn("文件MIME类型不匹配，但扩展名正确，继续处理");
  }

  // 限制文件大小（10MB）
  // const maxSize = 10 * 1024 * 1024; // 10MB
  // if (file.size && file.size > maxSize) {
  //   ElMessage.error('文件大小不能超过 10MB');
  //   return false;
  // }

  return true;
};
/**
 * 文件选择验证
 */
const handleFileSelect = (file: UploadFile) => {
  // 验证文件类型
  if (!validateFileType(file)) {
    // 清空文件选择
    if (uploadRef.value) {
      uploadRef.value.clearFiles();
    }
    return false;
  }

  // 文件验证通过，继续处理
  handleFileChange(file);
};
/**
 * 处理文件选择变化事件
 * @param file 上传的文件对象
 */
const handleFileChange = async (file: UploadFile) => {
  ElMessageBox.confirm(
    "该操作会覆盖当前系统下所有成品单位数据，确认继续？",
    "提示",
    {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      if (!file.raw) {
        return;
      }

      selectedFile.value = file.raw;
      importLoading.value = true;

      importTitle.value = "正在导入文件，请稍后...";
      try {
        // 调用导入API
        const formData = new FormData();
        formData.append("file", file.raw);
        // formData.append('deviceCode', currentNodeKey.value);

        const res = await "/api/deviceManufacturer/importExcel".post(formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        });
        if (res.code == 200) {
          ElMessage.success("导入成功");
          getList(); // 刷新列表
          resultDialogVisible.value = false;
        } else if (res.code == 299) {
          importTitle.value = "导入失败";
          // 验证数据
          tabs1.value = res.data;

          resultDialogVisible.value = true;
          importLoading.value = false;
        }
      } catch (error: any) {
        ElMessage.warning(error.data.msg);
      } finally {
        importLoading.value = false;
        // 清空文件选择
        if (uploadRef.value) {
          uploadRef.value.clearFiles();
        }
        selectedFile.value = null;
      }
    })
    .catch(() => {
      // 用户取消，清空文件选择
      if (uploadRef.value) {
        uploadRef.value.clearFiles();
      }
    });
};

/**
 * 导出数据
 */
const exportActionExcel = async () => {
  const res = await "/api/deviceManufacturer/downloadExcelTemplate".get(
    {},
    {
      responseType: "blob", // 指定响应类型为blob用于文件下载
    }
  );

  if (res.status === 200) {
    // ElMessage.success("导出成功");
    await handleFileDownload(res);
    ElMessage.success("导出成功，文件已开始下载");
  } else {
    ElMessage.warning(res.data?.msg || "导出失败");
  }
};

/**
 * 处理文件下载
 * @param res 响应对象
 */
const handleFileDownload = async (res: any) => {
  const blob = new Blob([res.data], {
    type: res.headers["content-type"] || "application/octet-stream",
  });

  // 获取文件名
  const contentDisposition = res.headers["content-disposition"];
  let filename = "dataExport";
  if (contentDisposition) {
    const filenameMatch = contentDisposition.match(/filename="?(.+)"?/);
    if (filenameMatch && filenameMatch.length === 2) {
      filename = decodeURIComponent(filenameMatch[1]);
    }
  }

  // 创建下载链接
  const url = window.URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.setAttribute("download", filename);
  document.body.appendChild(link);
  link.click();

  // 清理资源
  window.URL.revokeObjectURL(url);
  document.body.removeChild(link);
};
onMounted(() => {
  calculateHeights();
  window.addEventListener("resize", calculateHeights);
});
onUnmounted(() => {
  window.removeEventListener("resize", calculateHeights);
});
</script>

<style scoped lang="less">
:deep(.el-card) {
  height: 100%;
}

.operIcon {
  width: 20px !important;
}

:deep(.el-divider--horizontal) {
  margin: 5px 0 15px 0;
}

.action-buttons {
  display: flex;
  color: var(--el-color-primary);
}

.action-btn {
  flex: 1;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 4px;
}

.error-item {
  margin-bottom: 16px;
  padding: 12px;
  background: white;
  border-radius: 4px;
  border: 1px solid rgba(251, 198, 198, 1);
  background-color: rgba(254, 240, 240, 0.5);
  // border-left: 4px solid #f56c6c;

  h4 {
    color: #f56c6c;
    font-weight: bold;
  }

  p {
    // color: #606266;
    margin: 4px 0;
    padding-left: 8px;
    color: #f56c6c;
  }
}
.mb-10px {
  display: flex;
}
.opBtn-upload {
  display: inline-block;
  margin: 0 12px;
}
</style>
